<template>
    <!--新增角色组弹窗-->
        <el-dialog  :visible.sync="newDialogVisible" :show-close="false" width='753px' :class="['dialog','hiddenHeader']" >
            <div class="dialogTitle">
                {{dialogTitle}}
            </div>
            <i class="el-icon-error" @click='$emit("dialogVisibleChangeFn",false)'></i>
            <el-form v-if="newDialogVisible"   :model="ruleForm"  ref="ruleForm" label-width="175px" size='medium' class="demo-ruleForm">
                <el-form-item  v-for="(form,index) in ruleForm.formList" :key="index"  :label="form.label+'：'"  :prop="'formList.'+index+'.formValue'"  :rules="form.rules">
                    <el-row v-if="form.type=='pick'">
                        <el-col :span="24">
                            <el-radio v-model="form.formValue" :label="1"><span class="tip">{{ form.check1 }}</span></el-radio><br>
                            <el-select style="margin: 0 10px 0 25px; width: 180px;" v-model="dept"  placeholder="请先选择人">
                                 <el-option v-for="(item,index) in deptList" :key="index" :label="item.re_dept_name" :value="item.re_dept_id"></el-option>
                            </el-select>
                            <el-select style="width: 180px;" v-model="dept" placeholder="选择他所在的部门">
                              <el-option v-for="(item,index) in deptList" :key="index" :label="item.re_dept_name" :value="item.re_dept_id"></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="24">
                            <el-tag   :key="index" style="margin-right:5px"  v-for="(tag,index) in usrTags"  closable  :disable-transitions="false"   @close="usrTags.splice(index,1)">{{tag.name}}</el-tag>
                        </el-col>
                         <el-col :span="24">
                            <el-radio v-model="form.formValue" :label="2"><span class="tip">{{ form.check2 }}</span></el-radio><br>
                            <el-select style="margin: 0 10px 0 25px;width: 180px;" v-model="dept" placeholder="请选择部门">
                                  <el-option v-for="(item,index) in deptList" :key="index" :label="item.re_dept_name" :value="item.re_dept_id"></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="24">
                            <el-tag   :key="index" style="margin-right:5px"  v-for="(tag,index) in deptTags"  closable  :disable-transitions="false"   @close="deptTags.splice(index,1)">{{tag.name}}</el-tag>
                        </el-col>
                    </el-row>
                    <span v-if="form.type=='text'">{{ form.formValue }}</span>
                    <!-- 输入框 -->
                   <el-input v-if="form.type=='input'" style="width:200px;height:40px" :name="form.name" v-model="form.formValue" :placeholder="form.placeholder||'请输入'" :disabled="form.disabled||false" :maxlength="form.maxlength||64"></el-input>
                   <!-- 文本域-->
                   <el-input r v-if="form.type=='textarea'"  rows='5' :name="form.name" type="textarea"  v-model="form.formValue"  :placeholder="form.placeholder||'请输入'" :maxlength="form.maxlength||255" show-word-limit></el-input>
                   <!-- 数字输入框 -->
                   <el-input v-if="form.type=='number'" style="width:200px;height:40px" :name="form.name" v-model.number="form.formValue" :min='0' :step='0.01'  :placeholder="form.placeholder||'请输入数字'" :disabled="form.disabled" maxlength="10"></el-input>
                   <!-- 下拉选择框 -->
                   <el-select v-if="form.type=='select'" style="width:200px;height:40px" :name="form.name" v-model="form.formValue" :placeholder="form.placeholder" :disabled="form.disabled" @keyup.enter.native.prevent>
                        <template v-if="!form.hasOwnProperty('children')">
                            <el-option v-for="(item, i) in form.option" @keyup.enter.native.prevent :name="form.name" :key="`item-${i}`" ref="option" :disabled="item.disabled" :label="item[form.defaultProps.label]" :value="item[form.defaultProps.value]"></el-option>
                        </template>
                        <el-option class="newOption" ref="optionTree" v-else :name="form.name" :label="form.name" :value="form.value" >
                            <el-tree  :data="form.option"  :props="form.defaultProps" accordion @node-click="handleNodeClick($event,formIndex)">
                            </el-tree>
                        </el-option>
                    </el-select>
                    <ul class="mainlist" v-if="form.type=='upload'">
                        <li v-for="(list,idx) in form.formValue" :key="idx" @mouseenter="delshow=true;PicIndex=idx"  @mouseleave="delshow=false;PicIndex=''" >
                            <img class="img" :src="list" alt="" width="70px" height="70px">
                            <div class="delpic" v-if="delshow&&(PicIndex==idx)" >
                                <i @click.stop="delcouPicHan(index,idx)" class="el-icon-delete ii"></i> 
                                <i @click.stop="dialogImageUrl=list;dialogVisiblePic=true;" class="el-icon-zoom-in ii"></i> 
                            </div>
                        </li>
                        <li  @click.stop="upcouPic(index)"  v-loading.fullscreen.lock="fullscreenLoading">
                                 <i style="font-size:40px;color:rgb(217,217,217);font-weight:600" class="el-icon-plus"></i>
                        </li>
                    </ul>
                </el-form-item>
                <el-form-item class="onSubmitFormItem" style="text-align:right;margin:0">
                    <el-button @click="newDialogVisible=false" class="cancelBtn" onFocus="this.blur()">取消</el-button>
                    <el-button @click="onSubmit('ruleForm')" type="primary" :disabled="this.$store.state.disabled"  onFocus="this.blur()">{{'保存'}}</el-button>
                </el-form-item>
            </el-form>
            <!-- 图片预览 -->
            <el-dialog :visible.sync="dialogVisiblePic">
                <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
    </el-dialog>
</template>

<script>
 /* eslint-disable */ 
import {getRam,getCheckUser,getCheckDept} from "@/api" 
import OSS from 'ali-oss'
import fileUtil from '@/libs/fileUtil.js'
import {complexPicker,departmentsPicker} from '@/libs/utils'
export default {
    name:"dialogVue",
    data(){
        return {
            fullscreenLoading:false,
            newDialogVisible:this.dialogVisible,
            dialogVisiblePic:false,
            dialogImageUrl:'',
            delshow:false,
            PicIndex:'',
            usrTags:[],
            usrIds:[],
            deptTags:[],
            deptIds:[],
            deptList:[],/**同事的部门 */
            dept:'',/**选好的部门 */
        }
    },
    props:{
        noTurnMe:Boolean,
        dialogVisible:Boolean,
        wh_id:String,
        dialogTitle:String,
        ruleForm:Object,
    }, 
    created(){
       this.ruleForm.formList = this.formList
    },
    watch:{
        dialogVisible:{
            handler(news){
                this.newDialogVisible = news
                this.$store.commit('changeDisabled', false)
            },
            immediate: true,
        },
        newDialogVisible(val){

            this.usrTags = []
            this.deptTags = []
            this.deptIds =  ''
            this.usrIds = ''
            this.deptList = [],/**同事的部门 */
            this.dept = '',/**选好的部门 */

            this.$emit("dialogVisibleChangeFn",val)
            this.$store.commit('changeDisabled', false)
        },
    },
    methods:{
        /**选人 */
        pickMan(){
            let that = this
            complexPicker(this,
                {
                    useridArr:this.usrIds&&this.usrIds.length?this.usrIds.split(','):[],
                    bool:true,
                    maxUsers:1,
                    disabledUsers:[this.noTurnMe?this.$store.state.users.userid:'']},
            function(res){
                that.usrIds = res.user_id
                that.usrTags = res.users
                getCheckUser({userid:res.user_id,wh_id:that.wh_id}).then(res=>{
                    that.deptList = res
                    if(!res||(!res.length))this.$message.error('该用户没有部门，无法转移');
                    if(res&&(res.length==1))this.dept=res[0].re_dept_id
                })
            })
        },
        /**选部门 */
        pickDept(){
            let that = this
            // getCheckDept({wh_id:this.wh_id}).then(res=>{
                // departmentsPicker(this,{pickedDepartments:this.deptIds&&this.deptIds.length?this.deptIds.split(','):[],maxDept:1,disDept:res.dept_ids?res.dept_ids.split(','):[]},function(res){
                departmentsPicker(this,{pickedDepartments:this.deptIds&&this.deptIds.length?this.deptIds.split(','):[],maxDept:1},function(res){
                   that.deptIds = res.dept_id
                   that.deptTags = res.departments
               })
            // })
        },
        /*表单提交*/
        onSubmit(formName){
            this.$refs[formName].validate((valid) => {
                /*如果表单没有通过*/
                if (!valid) return false;
                /*表单验证通过*/
                this.$store.commit('changeDisabled', true)
                /**定义定义传输数据 */
                let formData = new FormData()
                // let formData = {}
                this.ruleForm.formList.forEach(element => {
                        element.type=='text'?'':formData.append(element.name,(typeof element.formValue)=='string'?element.formValue:JSON.stringify(element.formValue))
                });
                // if(!this.dept&&this.form.ts_type==1) return this.$message.error('转给同事则部门必填');
                if(this.ruleForm.addForm&&this.ruleForm.addForm.length){
                    this.ruleForm.addForm.forEach(ele=>{
                        formData.append(ele.name,JSON.stringify(ele.formValue))
                    })
                }
                /**抛出数据 */
                this.$emit('goSubmit',formData,this.usrTags,this.deptTags,this.dept);
                this.usrTags = []
                this.deptTags = []
                this.deptIds =  ''
                this.usrIds = ''
                this.deptList = [],/**同事的部门 */
                this.dept = ''/**选好的部门 */
                


            });
        },  
            //删除图片
        delcouPicHan(index,idx){
            this.ruleForm.formList[index].formValue.splice(idx, 1)
        },
          //图片上传
        upcouPic(val){
            if(this.ruleForm.formList[val].formValue.length<this.ruleForm.formList[val].limitNum){
                fileUtil.getFile({
                    multiple:true,
                    aaccept:"image/jpg,image/png", //文件类型， 非必填，默认值image/*
                    done:(files,src,dom)=>{
                        var file = Array.prototype.slice.call(files) 
                        let _this =this;
                        getRam().then(res=>{
                            var client = new OSS({
                                region: res.region,
                                accessKeyId: res.accessKeyId,
                                accessKeySecret: res.accessKeySecret,
                                bucket:  res.bucket
                            });
                            let arr = []
                            for(let i=0;i<file.length;i++){ /**循环上传 */
                                if(this.ruleForm.formList[val].formValue.length+i>=this.ruleForm.formList[val].limitNum){
                                    this.$message.warning(`当前限制选择 ${this.ruleForm.formList[val].limitNum} 个文件，请将不要的附件先进行删除`);
                                    break
                                } 
                                this.fullscreenLoading = true 
                                if(file[i].type.indexOf('image')>-1){
                                    let promise = client.multipartUpload((new Date().getTime())+file[i].name, file[i]).then(function(respond){
                                        _this.ruleForm.formList[val].formValue.push(res.url+respond.name)
                                    }).catch((err) => {
                                        this.fullscreenLoading = false 
                                    })
                                    arr.push(promise)
                                }else{
                                    return Toast('文件格式不对');
                                }
                            }
                            Promise.all(arr).then((result) => {
                                this.fullscreenLoading = false
                            }).catch(err=>{
                                this.fullscreenLoading = false
                            })
                        })
                    }
                })
            }else{
                this.$message.warning(`当前限制选择 ${this.ruleForm.formList[val].limitNum} 个文件，请将不要的附件先进行删除`);
            }
        },
    }
}
</script>

<style lang='stylus' >
.dialog
    .el-dialog
        min-width 753px
        position relative
        .dialogTitle
            line-height : 29px;
            color: rgba(16, 16, 16, 1);
            font-size: 20px;
            margin 0 0 50px 7px
            font-family: SourceHanSansSC-regular;
         .frontmsg
             position absolute
             left -161px
         .frontmsg::before
             content: '*';
             color: #F56C6C;
             margin-right: 4px;
        .textspan::before
             content: '*';
             color: #F56C6C;
             margin-right: 4px;
        .labels 
            position absolute
            left 38px
            top 122px
        .el-button--medium
            padding 10px 22px
        .el-button+.el-button
            margin-left 20px
        .el-icon-error
            font-size 22px 
            color rgb(206,206,206)
            position absolute
            right 14px 
            top 14px
            cursor pointer
        .el-col-24
            margin-bottom 10px
            .el-button--primary 
                width: 70px;
                height: 30px;
                line-height: 30px;
                border-radius: 3px;
                background-color: rgba(10, 142, 255, 1);
                color: rgba(255, 255, 255, 1);
                text-align: center;
                padding 0
                margin-right 10px
                >span 
                    font-size: 12px;
        .tip
            color: rgba(16, 16, 16, 1);
            font-size: 14px;
            font-family: SourceHanSansSC-regular;
        .el-dialog__header
            line-height 0
            background-color #F8F8F8
            padding 10px 10px 10px 68px
            display flex
            align-items center 
            .el-dialog__title
                font-size 16px 
                color rgba(0, 0, 0, 0.85)
            .el-dialog__headerbtn
                top 10px
                right 10px
                font-size 14px
        .el-dialog__body
            padding 33px 60px 47px 60px
        .el-form-item
            margin-bottom 22px
        &:last-child
            margin-bottom 0
        .dialog-footer
            display flex
            justify-content center
    .mainlist
        display: flex
        flex-wrap wrap
        li
            width 70px
            position relative
            height 70px
            cursor pointer
            margin 10px 10px 10px 0
        li:last-child 
            width 64px
            height 64px
            display flex
            align-items center
            justify-content center
            border 3px  dashed  rgb(217,217,217)
        .delpic
            height 70px;
            background rgba(0,0,0,0.5)
            position absolute
            display flex
            justify-content space-around
            align-items center
            right 0
            bottom 0
            z-index 100
            width: 70px;
            line-height 64px
            color #fff
            font-size 30px
.win-wid
    min-width 753px
.hiddenHeader
    .el-dialog
        .el-dialog__header
            display none

</style>